#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

// real malloc ptr
static void* (*real_malloc)(size_t) = nullptr;

/*
my malloc impl
it will result in infinite recursion, 
if direct or indirect calls to "malloc" in my "malloc",
eg: "printf"
*/
extern "C" void* malloc(size_t size) {
    //log buf
    char buf[128];
    if (!real_malloc) {
        real_malloc = reinterpret_cast<void*(*)(size_t)>(dlsym(RTLD_NEXT, "malloc"));
        if (!real_malloc) {
            int len = snprintf(buf, sizeof(buf), "Error in dlsym: %s\n", dlerror());
            write(STDERR_FILENO, buf, len);
            return nullptr;
        }
    }
    
    void* ptr = real_malloc(size);
    int len = snprintf(buf, sizeof(buf), "googluck malloc(%zu) = %p\n", size, ptr);
    write(STDERR_FILENO, buf, len);    
    return ptr;
}

/* cmd
g++ -shared -fPIC -o mymalloc.so hooker.cpp -ldl
export LD_PRELOAD=./mymalloc.so
// test
ls ./
*/